package cn.itsource.basic.service.impl;

import cn.itsource.basic.domain.BaseDomain;
import cn.itsource.basic.query.BaseQuery;
import cn.itsource.basic.service.IBaseService;
import cn.itsource.basic.util.PageList;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.common.Mapper;

import java.util.List;

/**
 * 注意
 * 1.千万不要加@service
 * 2.注入mapper一定要注入Tk的Mapper接口（框架抽好的）
 * @param <T>
 * @param <Q>
 *
 *     继承的时候注意两个原则
 *     1.接口继承接口可以删除6个方法
 *     2.实现类，只能删除没有改动业务的（和base一样的业务就可以删）
 */
public class BaseServiceImpl<T extends BaseDomain,Q extends BaseQuery>  implements IBaseService<T,Q>{

    @Autowired
    private Mapper<T> mapper;

    @Override
    public List<T> findAll() {
        return mapper.selectAll();
    }

    @Override
    public PageList<T> findPage(Q q) {

        //1.分页插件
        PageHelper.startPage(q.getPage(), q.getSize());

        //2.封装pageInfo
        List<T> ts = mapper.selectAll();
        PageInfo<T> pageInfo = new PageInfo<>(ts);

        //3.返回自己封装的PageList
        return new PageList<>(pageInfo.getTotal(),pageInfo.getList());
    }

    @Override
    public T findOne(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public void saveOrUpdate(T t) {
        if (t.getId() == null){
            mapper.insertSelective(t);
        }else{
            mapper.updateByPrimaryKeySelective(t);
        }
    }

    @Override
    public void delete(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public void batchRemove(Q q) {
        //1.获取到所有的ids
        Long[] ids = q.getIds();
        if (ids == null || ids.length == 0){
            return;
        }
        //2.遍历
        for (Long id : ids) {
            mapper.deleteByPrimaryKey(id);
        }
    }
}
